#pragma once
#include <allegro5\allegro_primitives.h>
#include "WorldMap.h"
#include "perlinNoise.h"

void WorldMap::generatePerlin(){
	// << WORLD TERRAIN GENERATOR >>
	// << http://www.dreamincode.net/forums/topic/66480-perlin-noise/ >>
	fprintf(stderr, "  - Perlin noise based generation...");

	// Parameters:
	int octaves = 8;
	int w = _tilesX;
	int h = _tilesY;
	double zoom = 50; //fractal zoom
	double p = 0.6; //persistence
	int waterLevel = 100;
	int minimalWaterPercent = 20;
	int maximalWaterPercent = 50;

	// Perlin noise generation
	int waterCount = 0;
	ALLEGRO_BITMAP* elevation = getPerlinNoise(w, h, zoom, p, octaves);
	ALLEGRO_BITMAP* moisture = getPerlinNoise(w, h, zoom*2, p, octaves);
	//al_draw_bitmap(elevation,10,10,0);
	//al_draw_bitmap(moisture,20+w,10,0);
	//al_flip_display();

	// Whittaker diagram adaptation for biomees
	EBiome whit[3][3] = 
	{
		{SAVANNA, DESERT, STEPPE},
		{TROPIC, FOREST, SCLEROPHYLL},
		{TAIGA, TUNDRA, POLAR}
	};

	// Converting bitmap to tile map
	al_lock_bitmap(elevation,ALLEGRO_PIXEL_FORMAT_ANY,ALLEGRO_LOCK_READWRITE);
	al_lock_bitmap(moisture,ALLEGRO_PIXEL_FORMAT_ANY,ALLEGRO_LOCK_READWRITE);
	for(int y=0; y<h; y++){
		for(int x=0; x<w; x++){
			unsigned char color = 255;

			al_unmap_rgb(al_get_pixel(elevation,x,y),&color,&color,&color);
			int elevationLevel = -1;
			color = color < waterLevel ? 0 : color-waterLevel;
			if(color > 0) elevationLevel = color/((255-waterLevel)/3 + 1);

			al_unmap_rgb(al_get_pixel(moisture,x,y),&color,&color,&color);
			int moistureLevel = color/(255/3 + 1);

			if(elevationLevel == -1){
				setLower(x,y,WATER);
				waterCount++;
			}
			else{
				setLower(x,y,whit[moistureLevel][elevationLevel]);
			}
		}
	}
	al_unlock_bitmap(elevation);
	al_unlock_bitmap(moisture);

	al_destroy_bitmap(elevation);
	al_destroy_bitmap(moisture);
	if(waterCount*100/(w*h) > maximalWaterPercent || waterCount*100/(w*h) < minimalWaterPercent){
		fprintf(stderr, "\r");
		generatePerlin();
	}
	else fprintf(stderr, " - OK\n");
}